﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 基于datatable的单据浏览窗体
    /// </summary>
    public partial class DocumentViewForm : DocumentViewForm<System.Data.DataRow, System.Data.DataTable>, IDocumentViewForm, IEventHandler<DocumentEventBase>
    {
        /// <summary>
        /// 构建基于datatable的单据浏览窗体实例。
        /// </summary>
        public DocumentViewForm() : base()
        {
            this.Load += this.DocumentViewForm_Load;
        }

        private void DocumentViewForm_Load(object sender, EventArgs e)
        {
            if (this.Controller != null)
            {
                IEventBus eventBus = Marmat.FrameWork.SystemCommand.GetService<IEventBus>();
                if (eventBus != null && !string.IsNullOrEmpty(this.Controller.Management.Name))
                    eventBus.Subscribe(this.Controller.Management.Name, this);
            }
        }

        Task IEventHandler<DocumentEventBase>.Handler(DocumentEventBase @event)
        {
            Task result = null;
            if (@event.Name == this.Controller.Management.Name)
            {
                Action action = () =>
                {
                    System.Data.DataTable data = this.bGridControl1.DataSource as System.Data.DataTable;
                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        object id = data.Rows[i][this.Controller.Management.Command.PrimaryName];
                        if (object.Equals(@event.Id, id))
                        {
                            System.Data.DataRow row = data.Rows[i];
                            System.Data.DataRow entity = this.Controller.Management.Command.Load(@event.Id);
                            foreach (System.Data.DataColumn column in data.Columns)
                            {
                                row[column] = entity[column.ColumnName];
                            }
                            row.AcceptChanges();
                            break;
                        }
                    }
                };
                result = Task.Run(() => this.Invoke(action));
            }
            return result;
        }
    }
}
